<?php
class Orders extends MY_Model {

    var $table_name = 'orders';
	var $primary_key = 'id';
	


	function get_orders($start,$limit,$where = null)
    {
    	if(empty($where))
    		$sql = "SELECT * FROM orders LIMIT $start,$limit";
    	else 
    		$sql = "SELECT * FROM orders WHERE $where LIMIT $start,$limit";
	    $query = $this->db->query($sql);
		return $query->result_array();
        
    }
	function get_full_details($id)
    {
    	$sql = "SELECT orders.*,applicant.full_name,applicant.gender,applicant.day_of_birth,applicant.nationality,applicant.passport_number,applicant.expiration_day FROM orders LEFT JOIN applicant ON orders.id = applicant.order_id WHERE orders.id = $id";
	    $query = $this->db->query($sql);
		return $query->result_array();
        
    }
    function check_isset($id){
    	$query = $this->db->query('SELECT count(*) as total FROM orders WHERE id='.$id);
		$row = $query->row_array();
        if($row['total']>0)
			return true;
		else return false;	
    }
    function insert_order($data)
    {
        $this->filterData($data);
        $this->db->insert('orders', $data);
        return $this->db->insert_id()  ;
    }
	function get_by_id($id)
    {
	    $this->db->where('id',$id);
		$query = $this->db->get("orders");
        return $query->row_array();
        
    }
    function update_order($data,$id)
    {
		$this->filterData($data);
        return $this->db->update('orders', $data, array('id' => $id));
    }
	function new_to_processing($id)
    {
        return $this->db->update('orders', array('status'=>'Processing'), array('id' => $id,'status'=>'New'));
    }
    function delete_order($id){
    	$this->db->trans_start();
		$this->db->query("DELETE FROM orders WHERE id = $id");
		$this->db->query("DELETE FROM applicant WHERE order_id = $id");
		$this->db->trans_complete(); 
    }
	protected function filterData(&$data){
		foreach($data as $key=>$row){
			if (!$this->db->field_exists($key, 'orders'))
			{
				unset($data[$key]);
			} 
		}
    }
}